// 路由守卫
import router from '@/router'
import store from '@/store'

// 处理接口返回回来的菜单，将其装到路由之中
const filterAsyncRoutes = (routes) => {
  let asyncRoutes = []
  routes.forEach((route) => {
    if (route?.menuDetailList?.length) {
      route.menuDetailList.forEach(item => {
        let item_router = {}
        item_router.meta = {
          menu: item.menuNameTwo
        }
        item_router.path = item.menuUrl
        try {
          item_router.component = require("@/views" + item.menuUrl + ".vue").default
        } catch (error) {
          console.log('error-路由异常', error);
        }
        asyncRoutes.push(item_router)
      })
    }
  });
  return asyncRoutes
}

const routerView = {
  render: (h) => h("router-view"),
};

// 动态添加路由
const add_route = (routes) => {
  filterAsyncRoutes(routes).forEach(route => {
    router.addRoute("main", route);
  })
}

// 设置路由白名单
const white_router = ['/login']
router.beforeEach(async (to, from, next) => {
  // 设置浏览器标题
  document.title = to.meta.menu || '小猴子'

  if (white_router.includes(to.path)) {
    next()
  } else {
    let userLoginToken = localStorage.getItem('userLoginToken')
    // vux中保存的菜单信息
    let menu_list = store.getters.menu_list

    // 判断token
    if (userLoginToken) {
      if (menu_list.length) {
        await next()
      } else {
        // 获取菜单列表
        let asyncRoutes = await store.dispatch('get_menu')
        
        if (asyncRoutes.errCode == 200) {
          add_route(asyncRoutes.data.userRoleMenu)
          await next({ ...to, replace: true });
        } else {
          await store.dispatch('login_out')
        }
      }
    } else {
      await store.dispatch('login_out')
    }
  }
})
